package com.engine.common.baseEntity.ResponseEntity;


import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.annotation.JSONField;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Data
@Component
public class ResponseMsg implements Serializable {

    //状态码
    @JSONField(ordinal = 1)
    @ApiModelProperty(value = "状态码",position = 1)
    private Integer status=0;
    //信息
    @JSONField(ordinal = 2)
    @ApiModelProperty(value = "信息",position = 2)
    private String message;
    //结果（可空）
    @JSONField(ordinal = 3)
    @ApiModelProperty(value = "结果",position = 3)
    private Object result;
    //时间戳
    @JSONField(ordinal = 4)
    @ApiModelProperty(value = "时间戳",position = 4)
    private LocalDateTime timestamp;

    public static ResponseMsg success(String message){
        ResponseMsg result=new ResponseMsg();
        result.setStatus(200);
        result.setMessage(message);
        result.timestamp=LocalDateTime.now();
        return result;
    }

    public static ResponseMsg fail(String message){
        ResponseMsg result=new ResponseMsg();
        result.setStatus(400);
        result.setMessage(message);
        result.timestamp=LocalDateTime.now();
        return result;
    }

    public static ResponseMsg noPermission(String message){
        ResponseMsg result=new ResponseMsg();
        result.setStatus(401);
        result.setMessage(message);
        result.timestamp=LocalDateTime.now();
        return result;
    }

    public static ResponseMsg error(String message){

        ResponseMsg result=new ResponseMsg();
        result.setStatus(500);
        result.setMessage(message);
        result.timestamp=LocalDateTime.now();
        return result;
    }

    public ResponseMsg status(Integer status)
    {
        this.status=status;
        return this;
    }

    public ResponseMsg message(String message)
    {
        this.message=message;
        return this;
    }

    public ResponseMsg addData(Object data)
    {
        this.result=data;
        return this;
    }

    public ResponseMsg newMapData()
    {
        this.result=new HashMap<String,Object>();
        return this;
    }

    public ResponseMsg addKV(String key, Object value)
    {
        Map<String,Object> map=(Map<String,Object>)this.result;
        map.put(key,value);
        return this;
    }

    public byte[] toJsonBytes(){
        return JSONObject.toJSONBytes(this);
    }

}
